import apiClient from "../apiClient";

enum Api {
	Upload = "/common/upload",
	UploadByUrl = "/common/uploadByUrl",
	AttachmentList = "/attachment/index",
	CategoryList = "/attachment_category/index",
	Config = "/common/config",
}

interface CategoryItem {
	id: number;
	name: string;
	createtime: number;
	updatetime: number;
	sort: number;
	status: string;
}

interface CategoryListResponse {
	total: number;
	items: CategoryItem[];
}

interface AttachmentItem {
	id: number;
	category_id: number;
	admin_id: number;
	user_id: number;
	url: string;
	imagewidth: string;
	imageheight: string;
	imagetype: string;
	imageframes: number;
	filename: string;
	filesize: number;
	mimetype: string;
	extparam: string;
	createtime: number;
	updatetime: number;
	uploadtime: number;
	storage: string;
	sha1: string;
	name: string | null;
	fullurl: string;
	category: CategoryItem | null;
}

interface AttachmentListResponse {
	total: number;
	items: AttachmentItem[];
}

interface SaveAttachmentData {
	name: string;
	url: string;
	category_id?: number;
}

interface SiteConfig {
	beian: string;
	website_logo: string;
	name: string;
	cs_name: string;
	cs_content: string;
	cs_image: string;
}

class CommonService {
	/**
	 * 上传单个文件
	 * @param file 文件对象
	 * @returns 返回文件URL
	 */
	async uploadFile(file: File) {
		const formData = new FormData();
		formData.append("file", file);
		return apiClient.post<string>({
			url: Api.Upload,
			data: formData,
			headers: {
				"Content-Type": "multipart/form-data",
			},
		});
	}

	/**
	 * 通过URL上传图片
	 * @param url 图片URL
	 * @returns 返回上传后的URL
	 */
	async uploadByUrl(url: string) {
		return apiClient.post<string>({
			url: Api.UploadByUrl,
			data: { url },
		});
	}

	/**
	 * 获取附件列表
	 * @param params 查询参数
	 */
	async getAttachmentList(params?: Record<string, any>) {
		return apiClient.get<AttachmentListResponse>({
			url: Api.AttachmentList,
			params,
		});
	}

	/**
	 * 获取分类列表
	 */
	async getCategoryList() {
		return apiClient.get<CategoryListResponse>({
			url: Api.CategoryList,
		});
	}

	/**
	 * 获取站点配置
	 */
	async getConfig() {
		return apiClient.get<SiteConfig>({
			url: Api.Config,
		});
	}
}

export const commonService = new CommonService();
export type { SiteConfig };
